//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import { GitExtraInfo, NodeData } from '../types';
import LocalNodeWrap from '../LocalNodeWrap';
import type { GitLabRelease } from "@/api/gitlab/release";
import { list_release } from "@/api/gitlab/release";
import { Button, Space, Table, Tag } from 'antd';
import { ExportOutlined, ReloadOutlined } from '@ant-design/icons';
import type { GitLabRepo } from "@/api/gitlab/repo";
import { get_repo } from "@/api/gitlab/repo";
import { get_type_name, type UserDataSourceInfo, type GitSourceInfo, get_source } from '@/api/user_dataview';
import { open as shell_open } from '@tauri-apps/api/shell';
import UserPhoto from '@/components/Portrait/UserPhoto';
import type { ColumnsType } from 'antd/lib/table';
import moment from 'moment';


const GitLabReleaseListNode = (props: NodeProps<NodeData>) => {
    const [releaseList, setReleaseList] = useState<GitLabRelease[]>([]);
    const [repoInfo, setRepoInfo] = useState<GitLabRepo | null>(null);
    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const loadRepoInfo = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const url = new URL(sourceInfo.baseUrl ?? "");
        const baseUrl = `${url.protocol}//${url.host}`;
        const extraInfo = props.data.extraInfo as GitExtraInfo;
        const res = await get_repo(baseUrl, sourceInfo.accessToken, extraInfo.repoName);
        setRepoInfo(res);
    };

    const loadReleaseList = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const url = new URL(sourceInfo.baseUrl ?? "");
        const baseUrl = `${url.protocol}//${url.host}`;
        const extraInfo = props.data.extraInfo as GitExtraInfo;
        const res = await list_release(baseUrl, sourceInfo.accessToken, extraInfo.repoName);
        setReleaseList(res);
    };

    const getSourceTypeName = () => {
        if (dataSource == undefined) {
            return "";
        }
        return get_type_name(dataSource.source_type);
    };

    const columns: ColumnsType<GitLabRelease> = [
        {
            title: "标题",
            width: 200,
            render: (_, row: GitLabRelease) => (
                <a href={row._links.self} target="_blank" rel="noreferrer">{row.name}&nbsp;<ExportOutlined /></a>
            ),
        },
        {
            title: "标签",
            width: 80,
            render: (_, row: GitLabRelease) => (
                <a href={row.commit.web_url} target="_blank" rel="noreferrer">{row.tag_name}&nbsp;<ExportOutlined /></a>
            ),
        },
        {
            title: "创建人",
            width: 150,
            render: (_, row: GitLabRelease) => (
                <a href={row.author.web_url} target="_blank" rel="noreferrer">
                    <Space>
                        <UserPhoto logoUri={row.author.avatar_url} style={{ width: "16px", borderRadius: "10px" }} />
                        <div>{row.author.name}&nbsp;<ExportOutlined /></div>
                    </Space>
                </a>
            ),
        },
        {
            title: "相关资产",
            render: (_, row: GitLabRelease) => (
                <Space style={{ flexWrap: "wrap" }}>
                    {row.assets.sources.map(source => (
                        <Tag key={source.format}>
                            <a href={source.url} target="_blank" rel="noreferrer">{source.format}</a>
                        </Tag>
                    ))}
                </Space>
            ),
        },
        {
            title: "创建时间",
            width: 120,
            render: (_, row: GitLabRelease) => moment(row.created_at).format("YYYY-MM-DD HH:mm"),
        },

    ];


    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(() => {
        if (dataSource != undefined) {
            loadRepoInfo();
            loadReleaseList();
        }
    }, [dataSource]);

    return (
        <LocalNodeWrap title={
            <Space>
                <span>{getSourceTypeName()}</span>
                <span>发行版列表</span>
                {repoInfo != null && (
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open(repoInfo.web_url);
                    }}>{repoInfo.path_with_namespace}</a>
                )}
            </Space>
        } nodeData={props} extraButtonList={[
            <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadReleaseList();
            }} title='刷新' />
        ]} canChangeBgColor={false}>
            <Table rowKey="tag_name" dataSource={releaseList} columns={columns} pagination={false} scroll={{ y: props.data.height - 100 }} className="nodrag nopan nowheel"
            />
        </LocalNodeWrap>
    );
};

export default GitLabReleaseListNode;